package com.spring.sunflower.main.fragment;

import android.Manifest;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.spring.sunflower.R;
import com.spring.sunflower.anchor.PersonalDetailActivity;
import com.spring.sunflower.base.BaseFragment;
import com.spring.sunflower.bean.NearbyBean;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.dialog.OnPermissionIntroClickListener;
import com.spring.sunflower.main.MainContract;
import com.spring.sunflower.main.adapter.NearbyAdapter;
import com.spring.sunflower.main.presenter.NearbyPresenter;
import com.spring.sunflower.util.LocationUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Kevin on 2021/5/28<br/>
 * <p>
 * Describe:<br/>
 */
public class NearbyFragment extends BaseFragment<NearbyPresenter> implements MainContract.NearbyView, OnLoadMoreListener, OnRefreshListener {
    private SmartRefreshLayout refreshLayout;
    private RecyclerView mRecyclerView;
    private List<NearbyBean.DatasBean> mData = new ArrayList<>();
    private NearbyAdapter mAdapter;
    private int pageIndex = 1;
    private boolean granted;
    private LinearLayout llGetLocation;
    private TextView tvGetLocation;
    private boolean permissionDeniedForever = false;
//    private Toolbar toolbar;
    @Override
    public int setLayoutResId() {
        return R.layout.fragment_nearby;
    }

    @Override
    public void initView() {
//        toolbar = mView.findViewById(R.id.toolBar);
//        StatusBarUtil.setPaddingSmart(mActivity, toolbar);
        refreshLayout = mView.findViewById(R.id.refreshLayout);
        mRecyclerView = mView.findViewById(R.id.rvRecyclerView);
        llGetLocation = mView.findViewById(R.id.llGetLocation);
        tvGetLocation = mView.findViewById(R.id.tvGetLocation);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new NearbyAdapter(R.layout.adapter_nearby, mData);
        mRecyclerView.setAdapter(mAdapter);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setOnRefreshListener(this);
        granted = XXPermissions.isGranted(mActivity, Manifest.permission.ACCESS_FINE_LOCATION);
    }

    @Override
    public void initData() {
    }

    @Override
    public void initListener() {
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                NearbyBean.DatasBean datasBean = mData.get(position);
                Intent intent = new Intent(getActivity(), PersonalDetailActivity.class);
                intent.putExtra(Constant.KEY_TARGET_ID, String.valueOf(datasBean.getMemberId()));
                startActivity(intent);
            }
        });
        tvGetLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (permissionDeniedForever) {
                    permissionDeniedTip();
                } else {
                    XXPermissions.with(mActivity)
                            .permission(Permission.ACCESS_FINE_LOCATION)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    requestLocationAndUpdate();
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    if (never) {
                                        permissionDeniedTip();
                                    } else {
                                        showToast("获取定位权限失败:(");
                                    }
                                }
                            });
                }
            }
        });
//        mAdapter.addChildClickViewIds(R.id.btnChat);
//        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
//                NearbyBean.DatasBean datasBean = mData.get(position);
//                Intent intent = new Intent(mActivity, ChatActivity.class);
//                intent.putExtra(Constant.C2C_USER_ID, datasBean.getMemberId());
//                intent.putExtra(Constant.C2C_SHOW_NAME, datasBean.getNickname());
//                intent.putExtra(Constant.C2C_DRAFT_TEXT, "");
//                intent.putExtra(Constant.C2C_FACE_URL, datasBean.getPhoto());
//                startActivity(intent);
//            }
//        });
    }

    private void permissionDeniedTip() {
        showPermissionIntroDialog("权限拒绝通知", "定位权限被永久拒绝，请手动打开定位权限", new OnPermissionIntroClickListener() {
            @Override
            public void onClickOK() {
                XXPermissions.startPermissionActivity(mActivity, Permission.ACCESS_FINE_LOCATION);
            }

            @Override
            public void onClickCancel() {
                permissionDeniedForever = true;
            }
        });
    }

    @Override
    public void loadData() {
        if (granted) {
            requestLocationAndUpdate();
        } else {
            llGetLocation.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
        }
    }

    private void requestLocationAndUpdate() {
        llGetLocation.setVisibility(View.GONE);
        refreshLayout.setVisibility(View.VISIBLE);
        LocationUtils locationUtils = LocationUtils.getInstance(mActivity);
        locationUtils.registerLocation();
        locationUtils.setOnLocationGetListener(new LocationUtils.OnLocationGetListener() {
            @Override
            public void onLocationGet(Map<String, String> map) {
                String latitude = map.get("latitude");
                String longitude = map.get("longitude");
                String city = map.get("city");
                String province = map.get("province");
                mPresenter.updateLocation(map);
            }
        });
    }

    @Override
    public NearbyPresenter setPresenter() {
        return new NearbyPresenter(this);
    }

    @Override
    public void showNearbyData(List<NearbyBean.DatasBean> data) {
        if (pageIndex == 1) {
            mData.clear();
            mAdapter.setList(data);
        } else {
            mAdapter.addData(data);
        }
    }

    @Override
    public void updateLocationSuccess() {
        LocationUtils.getInstance(mActivity).stop();
        mPresenter.getNearby(1);
    }

    @Override
    public void updateLocationFailed() {

    }

    @Override
    public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
        if (refreshLayout.isLoading()) {
            refreshLayout.finishLoadMore();
        }
        mPresenter.getNearby(++pageIndex);
    }

    @Override
    public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh();
        }
        pageIndex = 1;
        mPresenter.getNearby(1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(mActivity, Permission.ACCESS_FINE_LOCATION)) {
                requestLocationAndUpdate();
            } else {
                printD("hello");
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        granted = XXPermissions.isGranted(mActivity, Manifest.permission.ACCESS_FINE_LOCATION);
        if (granted) {
            requestLocationAndUpdate();
        } else {
            llGetLocation.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
        }
    }
}
